package so.shanku.essential.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import aym.util.getservicesdata.GetServicesDataQueue;
import aym.util.getservicesdata.GetServicesDataUtil;
import aym.util.json.JsonMap;
import aym.util.json.JsonParseHelper;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.umeng.socialize.bean.SocializeConfig;
import com.umeng.socialize.sso.UMSsoHandler;
import net.tsz.afinal.annotation.view.ViewInject;
import so.shanku.essential.R;
import so.shanku.essential.activity.base.BaseActivity;
import so.shanku.essential.activity.base.BaseUIActivity;
import so.shanku.essential.adapter.HotGoodsAdapter;
import so.shanku.essential.adapter.RelationProductAdapter;
import so.shanku.essential.app.MyApplication;
import so.shanku.essential.getdata.GetDataConfing;
import so.shanku.essential.getdata.GetDataQueue;
import so.shanku.essential.getdata.JsonKeys;
import so.shanku.essential.getdata.ShowGetDataError;
import so.shanku.essential.utils.*;
import striveen.util.used.view.view.gridview.PLA_AbsListView;
import striveen.util.used.view.view.gridview.PLA_AdapterView;
import striveen.util.used.view.view.gridview.XGridView;

import java.util.*;

/**
 * Created by Jaelyn on 2015/9/16 0016.
 * 商城主题
 */
public class ShopThemeActivity extends BaseActivity implements PLA_AdapterView.OnItemClickListener {
    /**
     * 男士女士（当其中一个数据为空，不显示男士女士，直接展示）
     */
    @com.lidroid.xutils.view.annotation.ViewInject(R.id.shop_man_or_woman)
    private LinearLayout shop_man_or_woman;
    private String vendorId; //店铺的id

    @ViewInject(id = R.id.xgv)
    private XGridView shop_goods_xgv;

    /**
     * head view
     */
    @ViewInject(id = R.id.back_iv, click = "back_iv_click")
    private ImageView back_iv;//
    @ViewInject(id = R.id.filter_iv, click = "filter_iv_clcik")
    private ImageView filter_iv;//
    @ViewInject(id = R.id.collect_tv, click = "collect_tv_click")
    private ImageView collect_tv;//
    @ViewInject(id = R.id.share_iv, click = "share_iv_click")
    private ImageView share_iv;//
    /**
     * head view
     */
    @com.lidroid.xutils.view.annotation.ViewInject(R.id.shop_bg_iv)
    private ImageView shop_bg_iv;//主题图片
    @com.lidroid.xutils.view.annotation.ViewInject(R.id.shop_name_tv)
    private TextView shop_name_tv;//主题
    @com.lidroid.xutils.view.annotation.ViewInject(R.id.shop_discri_tv)
    private TextView shop_discri_tv;//主题描述
    @com.lidroid.xutils.view.annotation.ViewInject(R.id.shop_detail_tv)
    private TextView shop_detail_tv;//详情介绍

    /**
     * 热门商品的布局
     */
    @com.lidroid.xutils.view.annotation.ViewInject(R.id.hot_goods_layout)
    private LinearLayout hot_goods_layout;
//	@com.lidroid.xutils.view.annotation.ViewInject(R.id.shop_hot_goods_title_tv)
//	private TextView shop_hot_goods_title_tv;//热门商品的title

    @com.lidroid.xutils.view.annotation.ViewInject(R.id.shop_hot_goods_vp)
    private ViewPager shop_hot_goods_vp; //商品的图片
    @com.lidroid.xutils.view.annotation.ViewInject(R.id.view_ind_layout)
    private LinearLayout view_ind_layout;     //指示器
    /**
     * 定时器
     */
    private Timer timer;
    private FulstTimerTask timerTask;
    @com.lidroid.xutils.view.annotation.ViewInject(R.id.manType_tv)
    private TextView manType_tv;//男士
    @com.lidroid.xutils.view.annotation.ViewInject(R.id.womanType_tv)
    private TextView womanType_tv;//女士

    private List<JsonMap<String, Object>> manDatas = new ArrayList<JsonMap<String, Object>>();
    private List<JsonMap<String, Object>> womanDatas = new ArrayList<JsonMap<String, Object>>();
    private int manCurrentPage = 0;
    private int womanCurrentPage = 0;
    private boolean manCanLoadMore = true;
    private boolean womanCanLoadMore = true;
    private int pageSize = 10;
    private int typeId = 1;//男女类型 1：男士 2：女士
    /**
     * 下拉刷新Gridview适配器
     */
    private RelationProductAdapter productDetailAdapter;

    /**
     * 商品图片展示图
     */
    private HotGoodsAdapter hotGoodsAdapter;
    private List<JsonMap<String, Object>> hotGoodsDatas;
    private JsonMap brandDatas; //店铺信息

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.shoplayout);
        addHeadView();

        vendorId = getIntent().getStringExtra(Constant.ID);
        int themeType = getIntent().getIntExtra(ExtraKeys.Key_Msg1, 1);
        if (themeType == 1) {
            filter_iv.setVisibility(View.GONE);
        }
        typeId = 1;
        getThemeDetail();
        shop_goods_xgv.setOnScrollListener(new XGridView.OnXScrollListener() {
            @Override
            public void onXScrolling(View view) {
                int scrollY = view.getScrollY();
                int top = view.getTop();
                float y = view.getY();
                int height = view.getHeight();

                LogUtil.d(TAG, "scrollY:" + scrollY + "  top:" + top + "  getY:" + y + "  getHeight:" + height);
            }

            @Override
            public void onScrollStateChanged(PLA_AbsListView view, int scrollState) {

            }

            @Override
            public void onScroll(PLA_AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                int scrollY = view.getScrollY();
                int top = view.getTop();
                float y = view.getY();
                int height = view.getHeight();

                LogUtil.d(TAG, "scrollY:" + scrollY + "  top:" + top + "  getY:" + y + "  getHeight:" + height);
            }
        });
    }


    private void setSelection(int typeId) {
        this.typeId = typeId;
        if (typeId == 1) {
            manType_tv.setSelected(true);
            womanType_tv.setSelected(false);
        } else {
            manType_tv.setSelected(false);
            womanType_tv.setSelected(true);
        }
    }


    /**
     * 选择男士
     *
     * @param view
     */
    @OnClick(R.id.manType_tv)
    public void manType_tv_click(View view) {
        if (this.typeId == 1) {
            return;
        }
        setSelection(1);
        if (manDatas == null || manDatas.size() == 0) {
            manCurrentPage = 0;
            getRelationGoods();
        } else {
            setAdatper_data();
        }
    }

    /**
     * 选择女士
     *
     * @param view
     */
    @OnClick(R.id.womanType_tv)
    public void womanType_tv_click(View view) {
        if (this.typeId == 2) {
            return;
        }
        setSelection(2);
        if (womanDatas == null || womanDatas.size() == 0) {
            womanCurrentPage = 0;
            getRelationGoods();
        } else {
            setAdatper_data();
        }
    }


    //顶部切换时调用 刷新listview数据
    private void setAdatper_data() {
        if (typeId == 1) {
            shop_goods_xgv.setPullLoadEnable(manCanLoadMore);
            productDetailAdapter.setDatas(manDatas);
        } else {
            shop_goods_xgv.setPullLoadEnable(womanCanLoadMore);
            productDetailAdapter.setDatas(womanDatas);
        }
        productDetailAdapter.notifyDataSetChanged();

    }

    /**
     * 添加头部
     */
    private void addHeadView() {
        View headView = getLayoutInflater().inflate(R.layout.shop_theme_head_layout, null);
        ViewUtils.inject(this, headView);
        shop_goods_xgv.addHeaderView(headView);
        productDetailAdapter = new RelationProductAdapter(this);
        productDetailAdapter.setDatas(manDatas);
        shop_goods_xgv.setAdapter(productDetailAdapter);
        shop_goods_xgv.setPullRefreshEnable(false);
        shop_goods_xgv.setPullLoadEnable(true);
        shop_goods_xgv.setOnItemClickListener(this);
        shop_goods_xgv.setXListViewListener(loadMoreListener);
    }

    private XGridView.IXListViewListener loadMoreListener = new XGridView.IXListViewListener() {
        @Override
        public void onRefresh() {

        }

        @Override
        public void onLoadMore() {
            getRelationGoods();
        }
    };

    /**
     * 获取店铺详情    {VendorId:12,UserInfoId:123}
     */
    private void getThemeDetail() {
        loadingToast.show();
        Map<String, Object> params = new HashMap<String, Object>();
        params.put(GetDataQueue.Params_key, GetDataConfing.Key_Str);
        if (Utils.isHasLogin(this)) {
            params.put("UserInfoId", Utils.getUserId(this));
        }
        params.put("VendorId", vendorId);
        GetDataQueue queue = new GetDataQueue();
        queue.setActionName(GetDataConfing.GetAction_GetVendorDetails);
        queue.setParamsNoJson(params);
        queue.setCallBack(callBack);
        queue.setWhat(GetDataConfing.What_GetVendorDetails);
        getDataUtil.getData(queue);
    }


    /**
     * 获取商品  {VendorId:165,TypeId:2,currentPage:1,pageSize:10}
     */
    private void getRelationGoods() {
        loadingToast.show();
        //shop_goods_xgv.setBoolInterceptTouchEvent(false);

        Map<String, Object> params = new HashMap<String, Object>();
        params.put(GetDataQueue.Params_key, GetDataConfing.Key_Str);

        if (typeId == 1) {
            params.put("currentPage", manCurrentPage + 1);
        } else {
            params.put("currentPage", womanCurrentPage + 1);
        }
        params.put("pageSize", pageSize);
        params.put("VendorId", vendorId);
        params.put("TypeId", typeId);
        GetDataQueue queue = new GetDataQueue();
        queue.setActionName(GetDataConfing.GetAction_SelectVendorProductList);
        queue.setParamsNoJson(params);
        queue.setCallBack(callBack);
        queue.setWhat(GetDataConfing.What_SelectVendorProductList);
        getDataUtil.getData(queue);
    }


    private JsonMap shopIntroductMsg;  //用来跳转到店铺介绍页面
    private GetServicesDataUtil.IGetServicesDataCallBack callBack = new GetServicesDataUtil.IGetServicesDataCallBack() {

        @Override
        public void onLoaded(GetServicesDataQueue entity) {
            if (entity.isOk()) {
                if (ShowGetDataError.isCodeSuccess(mContext, entity.getInfo())) {
                    if (entity.what == GetDataConfing.What_SelectVendorProductList) {
                        stopload();
                        List<JsonMap<String, Object>> data_server = JsonParseHelper.getJsonMap_List_JsonMap(entity.getInfo(), JsonKeys.Key_Info);
                        setData(data_server);
                        validateData(data_server);
                    } else if (entity.what == GetDataConfing.What_GetVendorDetails) {
                        try {
                            JsonMap goodsDatas = JsonParseHelper.getJsonMap_List_JsonMap(entity.getInfo(), JsonKeys.Key_Info).get(0);
                            shopIntroductMsg = goodsDatas;
                            refreshShopDetail(goodsDatas);
                        } catch (Exception e) {
                            e.printStackTrace();
                            toast.showToast(R.string.server_error);
                            finish();
                        }

                    } else if (entity.what == GetDataConfing.WHAT_GET_FOCUS_ON) { //关注平拍
                        JsonMap<String, Object> data = JsonParseHelper
                                .getJsonMap(entity.getInfo());
                        try {
                            String msg = data.getString(JsonKeys.Key_Msg);
                            JsonMap temp = data.getList_JsonMap(JsonKeys.Key_Info).get(0);
                            String vendorId = temp.getStringNoNull("VendorId");
                            //toast.showToast(msg);

                            if (temp.getBoolean("IsFocus")) {
                                updateAttentionStatues(vendorId, true);
                            } else {
                                //removeFavourtePrograme(programId);
                                //jiemu_collect.setImageResource(R.drawable.icon_collect_no);
                                updateAttentionStatues(vendorId, false);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                } else {
                    if (entity.what == GetDataConfing.What_SelectVendorPostList) {
                        stopload();
                    }
                }
            } else {
                if (entity.what == GetDataConfing.What_SelectVendorPostList) {
                    stopload();
                }
                ShowGetDataError.showNetError(mContext);
            }
            loadingToast.dismiss();
        }

    };

    /**
     * 设置主题信息 并请求相关商品的信息
     *
     * @param goodsDatas
     */
    private void refreshShopDetail(JsonMap goodsDatas) {
        brandDatas = goodsDatas;

        String backImge = goodsDatas.getStringNoNull("BackGroundImage");   //背景大图
        if (MyApplication.getInstance().getBitmapHashMap().containsKey(backImge)) {
            shop_bg_iv.setImageBitmap(MyApplication.getInstance().getBitmapHashMap().get(backImge));
        } else {
            ImageLoader.getInstance().displayImage(backImge, shop_bg_iv, MyApplication.getInstance().getShopBgOption(), new ImageLoaderBitmapCallBack());
        }

        boolean isFocus = goodsDatas.getBoolean("isCollection");


//        hotGoodsDatas = goodsDatas.getList_JsonMap("HotProduct");
//        if (hotGoodsDatas.isEmpty()) {
//            hot_goods_layout.setVisibility(View.GONE);
//        } else {
//            hot_goods_layout.setVisibility(View.VISIBLE);
//            hotGoodsAdapter = new HotGoodsAdapter(this, hotGoodsDatas);
//            hotGoodsAdapter.setOnItemClickListener(new HotGoodsAdapter.OnItemClickListener() {
//                @Override
//                public void onItemClick(int index) {
//                    String goodsId = hotGoodsDatas.get(index).getStringNoNull("ProductId");
//                    seeProductDetail(goodsId);
//                }
//            });
//            hotGoodsAdapter.setIndContainerView(view_ind_layout);
//            shop_hot_goods_vp.setOnPageChangeListener(hotGoodsAdapter);
//            //adapter.setIndContainerView(shoppingHolder.goods_CircleFlowIndicator);
//            shop_hot_goods_vp.setAdapter(hotGoodsAdapter);
//            shop_hot_goods_vp.setCurrentItem(0);
//			if (hotGoodsDatas.size() > 1) {
//				//timer.schedule(timerTask, 3000, 3000);
//				shop_hot_goods_vp.setOnTouchListener(new View.OnTouchListener() {
//
//					@Override
//					public boolean onTouch(View v, MotionEvent event) {
//						if (event.getAction() == MotionEvent.ACTION_DOWN) {
//							isDown = true;
//						} else if (event.getAction() == MotionEvent.ACTION_UP) {
//							time = System.currentTimeMillis();
//							isDown = false;
//						}
//						return false;
//					}
//				});
//			}
//        }
        shop_name_tv.setText(goodsDatas.getStringNoNull("BrandName"));
        //shop_discri_tv.setText("\t\t\t\t"+goodsDatas.getStringNoNull("VendorInfo"));
        shop_detail_tv.setText("\t\t\t\t"+goodsDatas.getStringNoNull("VendorInfo"));
        String mrCount = goodsDatas.getStringNoNull("MrCount", "0");
        String msCount = goodsDatas.getStringNoNull("MsCount", "0");
        String mrTitle = String.format(getString(R.string.shop_man), mrCount);
        String msTitle = String.format(getString(R.string.shop_woman), msCount);

        manType_tv.setText(mrTitle);
        womanType_tv.setText(msTitle);
        if (mrCount.equals("0") || msCount.equals("0")) {
            shop_man_or_woman.setVisibility(View.GONE);
//            if (!mrCount.equals("0")) {
//                typeId = 1;
//
//            } else if (!msCount.equals("0")) {
//                typeId = 2;
//
//            }
            typeId=1;
            getRelationGoods();
        } else {
            shop_man_or_woman.setVisibility(View.VISIBLE);
            setSelection(1);
            getRelationGoods();
        }
    }

    /**
     * 定时刷新倒计时
     */
    private class FulstTimerTask extends TimerTask {

        @Override
        public void run() {
            handler.sendEmptyMessage(0);
        }
    }

    /**
     * 是否有手指点击在广告上
     */
    private boolean isDown = false;
    private long time;
    private boolean isFulshGuangGao = true;
    /**
     * 定时刷新倒计时执行者
     */
    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            // fulsuQiangGouShiJian();
            /*
             * 隔两秒刷新广告
			 */
            isFulshGuangGao = (!isFulshGuangGao);
            if (isFulshGuangGao && !isDown
                    && System.currentTimeMillis() - time > 1000) {
                if (shop_hot_goods_vp == null || shop_hot_goods_vp.getChildCount() == 0) {
                    return;
                }
                int defSelect = shop_hot_goods_vp.getCurrentItem();

                defSelect++;
                defSelect = defSelect % shop_hot_goods_vp.getChildCount();
                shop_hot_goods_vp.setCurrentItem(defSelect, true);

            }

        }

        ;
    };


    private void setData(List<JsonMap<String, Object>> data_server) {
        if (typeId == 1) {

            if (manCurrentPage == 0) {
                manDatas = data_server;
                productDetailAdapter = new RelationProductAdapter(this);
                productDetailAdapter.setDatas(data_server);
                shop_goods_xgv.setAdapter(productDetailAdapter);
            } else {
                manDatas.addAll(data_server);
                productDetailAdapter.notifyDataSetChanged();
            }
            manCurrentPage++;
        } else {

            if (womanCurrentPage == 0) {
                womanDatas = data_server;
                productDetailAdapter = new RelationProductAdapter(this);
                productDetailAdapter.setDatas(data_server);
                shop_goods_xgv.setAdapter(productDetailAdapter);
            } else {
                womanDatas.addAll(data_server);
                productDetailAdapter.notifyDataSetChanged();
            }
            womanCurrentPage++;
        }
    }

    private void setRefreshStatus(boolean isCanPull) {
        //programs_grid.setPullRefreshEnable(isCanRefresh);
        //programs_grid.setPullLoadEnable(isCanPull);
        shop_goods_xgv.setPullLoadEnable(isCanPull); //下拉刷新
    }

    /**
     * 校验数据 显示无数据等
     *
     * @param data_server
     */
    private void validateData(List<JsonMap<String, Object>> data_server) {
        if (typeId == 1) {
            if (data_server.size() == 0 || data_server.size() % pageSize != 0) {
                setRefreshStatus(false);
                manCanLoadMore = false;
            }

        } else {
            if (data_server.size() == 0 || data_server.size() % pageSize != 0) {
                setRefreshStatus(false);
                womanCanLoadMore = false;
            }
        }
    }

    private void stopload() {
        shop_goods_xgv.stopLoadMore();
    }


    public void back_iv_click(View view) {
        finish();
    }

    /**
     * 分享的点击事件
     *
     * @param view
     */
    public void share_iv_click(View view) {
        JsonMap jsonMap_temp = brandDatas;
        String shareLogo = jsonMap_temp.getStringNoNull("brandLogo");
        String shareTitle = jsonMap_temp.getStringNoNull("ShopName");
        String shareContent = jsonMap_temp.getStringNoNull("VendorInfo");
        String shareUrl = "ShopMall/Index?vid=" + vendorId;

        MyApplication.getInstance().showShareCompont(mContext, shareLogo, shareUrl, shareTitle, shareContent);
    }

    /**
     * 筛选
     *
     * @param view
     */
    public void filter_iv_clcik(View view) {

    }

    /**
     * 收藏的点击事件
     *
     * @param view
     */
    public void collect_tv_click(View view) {
        changeGoodsCollect(vendorId, callBack);
    }


    /**
     * 商品点击
     *
     * @param view
     */
    @Override
    public void onItemClick(PLA_AdapterView<?> parent, View view, int position, long id) {
        if (position > 1) {
            if (typeId == 1) {
                JsonMap jsonmap = manDatas.get(position - 2);
                String goodsId = jsonmap.getStringNoNull("ProductId");
                seeProductDetail(goodsId);
            } else {
                JsonMap jsonmap = womanDatas.get(position - 2);
                String goodsId = jsonmap.getStringNoNull("ProductId");
                seeProductDetail(goodsId);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /**使用SSO授权必须添加如下代码 */

//		UMSocialService umSocialService=MyApplication.getInstance().getmController();
//		if(umSocialService!=null) {
//			UMSsoHandler ssoHandler =umSocialService.getConfig().getSsoHandler(requestCode);
//			if (ssoHandler != null) {
//				ssoHandler.authorizeCallBack(requestCode, resultCode, data);
//			}
//		}
        UMSsoHandler ssoHandler = SocializeConfig.getSocializeConfig().getSsoHandler(requestCode);
        if (ssoHandler != null) {
            ssoHandler.authorizeCallBack(requestCode, resultCode, data);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopTimer();
    }

    private void stopTimer() {
        if (timer != null) {
//			try {
//				timerTask.cancel();
//				timer.cancel();
//				timerTask = null;
//				timer = null;
//			} catch (Exception e) {
//				e.printStackTrace();
//			}
        }
    }
}